import React, { useContext,useEffect,useRef,useState } from 'react'
import styles from './index.module.scss'
import Backdrop from '../../Backdrop'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faTrash } from '@fortawesome/free-solid-svg-icons'
import Meal from '../../Meals/Meal'
import { Context } from '../../../App'
import Confirm from '../Confirm'

export default function CartDetail({cancelDetail}) {
	const [showConfirm, setShowConfirm] = useState(false)
	const { cartData, clearCart } = useContext(Context)
	const headerRef = useRef(null)

	const toggleConfirm = () => {
		setShowConfirm(state => !state)
	}

	const onOk =() => {
		clearCart()
		setShowConfirm(false)
		headerRef.current.style.display = 'none'
		cancelDetail()
	}

	useEffect(() => {
		if(cartData.totalTotal === 0) {
			headerRef.current.style.display = 'none'
			cancelDetail()
		}
	}, [cartData.totalTotal]) 

	return (
		<Backdrop>
			<div className={styles.root} onClick={e => e.stopPropagation()} ref={headerRef}>
				{showConfirm && <Confirm title={'您确定要删除吗?'} onCancel={() => setShowConfirm(false)} onOk={onOk}/>}
				<header>
					<h2>餐品详情</h2>
					<div className="clearWrapper" onClick={toggleConfirm}>
						<FontAwesomeIcon icon={faTrash} className="icon" />
						<span>清空购物车</span>
					</div>
				</header>

				<div className="cartList">
					{cartData.items.map((item) => (
						<Meal key={item.id} meal={item} noDes={true} />
					))}
				</div>
			</div>
		</Backdrop>
	)
}
